using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Security;
using System.Resources;
namespace spktNhom4DoAnCuoiKy.ManagerModules
{
    public partial class UserManagement : System.Web.UI.Page
    {
        
        private void FillData()
        {
            AuctionOnlineDataContext db = new AuctionOnlineDataContext();
           
            //keeping sort
            
            if (ViewState["SortExpression"] != null && ViewState["SortDirection"] != null)
            {

                var users = db.aspnet_Users.Select(x => new { Username = x.UserName, LoaiNguoiDung = Session.getResourceManager().GetString(x.aspnet_UsersInRoles.FirstOrDefault().aspnet_Role.RoleName), TinhTrang = x.aspnet_Membership.IsApproved ? Session.getResourceManager().GetString("um_ChuaKichHoat") : Session.getResourceManager().GetString("um_DaKichHoat"), SoLanThamGia = x.LichSuDauGias.Count(), SoLanThang = x.LichSuDauGias.Where(y => y.TinhTrangPhien.MaTinhTrang == 1).Count(), KichHoat = x.aspnet_Membership.IsApproved ? "Kích Hoạt" : "Tạm Ngưng" }).OrderBy(ViewState["SortExpression"].ToString(), ViewState["SortDirection"].ToString() == "ASC" ? SortDirection.Ascending : SortDirection.Descending).ToList();
                gvQuanLyNguoiDung.DataSource = users;
            }
            else
            {
                var users = db.aspnet_Users.Select(x => new { Username = x.UserName, LoaiNguoiDung = Session.getResourceManager().GetString(x.aspnet_UsersInRoles.FirstOrDefault().aspnet_Role.RoleName), TinhTrang = x.aspnet_Membership.IsApproved ? Session.getResourceManager().GetString("um_ChuaKichHoat") : Session.getResourceManager().GetString("um_DaKichHoat"), SoLanThamGia = x.LichSuDauGias.Count(), SoLanThang = x.LichSuDauGias.Where(y => y.TinhTrangPhien.MaTinhTrang == 1).Count(), KichHoat = x.aspnet_Membership.IsApproved ? "Kích Hoạt" : "Tạm Ngưng" }).ToList();
                gvQuanLyNguoiDung.DataSource = users;
            }
            
            gvQuanLyNguoiDung.DataBind();
            ControlGoToPage.PageCount = gvQuanLyNguoiDung.PageCount;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //get rowPerPage
            int rowPerPage = int.Parse(ddlRowPerPage.SelectedValue);
            if (IsPostBack) Session["UsermanagementRowPerPage"] = rowPerPage.ToString();

            if (Session["UsermanagementRowPerPage"] != null)
                rowPerPage = int.Parse(Session["UsermanagementRowPerPage"].ToString());
            else Session["UsermanagementRowPerPage"] = rowPerPage;
            ddlRowPerPage.SelectedValue = rowPerPage.ToString();
                gvQuanLyNguoiDung.PageSize = rowPerPage;
                FillData();
               
            
          
            
        }

        protected void gvQuanLyNguoiDung_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label label = (Label)e.Row.FindControl("STT");
                if (label != null) {
                    label.Text = (gvQuanLyNguoiDung.PageIndex*gvQuanLyNguoiDung.PageSize+e.Row.RowIndex + 1).ToString();
                }
            }
        }

      

       
        private SortDirection GetSortDirection(string column)
        {

            // By default, set the sort direction to ascending.
            string sortDirection = "ASC";

            // Retrieve the last column that was sorted.
            string sortExpression = ViewState["SortExpression"] as string;

            if (sortExpression != null)
            {
                // Check if the same column is being sorted.
                // Otherwise, the default value can be returned.
                if (sortExpression == column)
                {
                    string lastDirection = ViewState["SortDirection"] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }

            // Save new values in ViewState.
            ViewState["SortDirection"] = sortDirection;
            ViewState["SortExpression"] = column;
            if (sortDirection == "ASC") return SortDirection.Ascending;
            return SortDirection.Descending;
        }
       

        protected void gvQuanLyNguoiDung_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvQuanLyNguoiDung.PageIndex = e.NewPageIndex;
            
            gvQuanLyNguoiDung.DataBind();

        }
        private int getColumnIndexByName(GridView gridview,string name){
            for (int i = 0; i < gridview.Columns.Count; i++)
            {
                if (gridview.Columns[i].SortExpression.ToLower() == name.ToLower().Trim())
                {
                    return i;
                }
                gridview.Columns[i].HeaderText = removeUpDownArrow(gridview.Columns[i].HeaderText); 
            }
            return -1;
        }
        private string removeUpDownArrow(string s)
        {
            return s.Replace("↑", "").Replace("↓","");
        }
        protected void gvQuanLyNguoiDung_Sorting1(object sender, GridViewSortEventArgs e)
        {
            
            AuctionOnlineDataContext db = new AuctionOnlineDataContext();
            SortDirection sortd;
            var users = db.aspnet_Users.Select(x => new { Username = x.UserName, LoaiNguoiDung = Session.getResourceManager().GetString(x.aspnet_UsersInRoles.FirstOrDefault().aspnet_Role.RoleName), TinhTrang = x.aspnet_Membership.IsApproved ? Session.getResourceManager().GetString("um_ChuaKichHoat") : Session.getResourceManager().GetString("um_DaKichHoat"), SoLanThamGia = x.LichSuDauGias.Count(), SoLanThang = x.LichSuDauGias.Where(y => y.TinhTrangPhien.MaTinhTrang == 1).Count(), KichHoat = x.aspnet_Membership.IsApproved ? Session.getResourceManager().GetString("um_KichHoat") : Session.getResourceManager().GetString("um_TamNgung") }).OrderBy(e.SortExpression, sortd = GetSortDirection(e.SortExpression)).ToList();

            int indexColumnSort = getColumnIndexByName(gvQuanLyNguoiDung, e.SortExpression);
            if (sortd == SortDirection.Ascending)
            {
                gvQuanLyNguoiDung.Columns[indexColumnSort].HeaderText = removeUpDownArrow(gvQuanLyNguoiDung.Columns[indexColumnSort].HeaderText) + "↑";
            }
            else
            {
                gvQuanLyNguoiDung.Columns[indexColumnSort].HeaderText = removeUpDownArrow(gvQuanLyNguoiDung.Columns[indexColumnSort].HeaderText) + "↓";
            }

            gvQuanLyNguoiDung.DataSource = users;
            gvQuanLyNguoiDung.DataBind();
            
        }

        protected void gvQuanLyNguoiDung_DataBound(object sender, EventArgs e)
        {
            if (gvQuanLyNguoiDung.PageCount == 1) ControlGoToPage.Visible = false;
            else ControlGoToPage.Visible = true;
        }

        protected void gvQuanLyNguoiDung_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EnDisableStatus")
            {
                string username = e.CommandArgument.ToString();
                  AuctionOnlineDataContext db = new AuctionOnlineDataContext();
                  aspnet_User user = db.aspnet_Users.Where(x => x.UserName == username).FirstOrDefault();
                  user.aspnet_Membership.IsApproved = !user.aspnet_Membership.IsApproved;
                  db.SubmitChanges();
                  FillData();
  
            }
        }
        protected void GoToPage_Clicked(object sender, GoClickedEventArgs e)
        {
            //if (e.NextPage - 1 > gvQuanLyNguoiDung.PageCount)
            //{
            //    Response.Write("<script>alert('số bạn nhập vượt quá số trang.');</script>");
            //    return;
            //}
          
            gvQuanLyNguoiDung.PageIndex = e.NextPage-1;
            gvQuanLyNguoiDung.DataBind();
        }

        protected void ddlRowPerPage_SelectedIndexChanged(object sender, EventArgs e)
        {
            gvQuanLyNguoiDung.PageSize = int.Parse(ddlRowPerPage.SelectedValue);
            FillData();
        }

    }
}